using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class AudioManager :SingletonPattern<AudioManager>
{
    public AudioManager()
    {
        PublicMonoManager.Instance.AddUpdateListener(Update);
    }

    private AudioSource backMusic = null;

    private GameObject soundObj = null;
    private List<AudioSource> soundList = new List<AudioSource>();

    private void Update()
    {
        for (int i = soundList.Count-1; i >=0; i--)
        {
            if (soundList[i].isPlaying)
            {
                GameObject.Destroy(soundList[i]);
                soundList.RemoveAt(i);
            }
        }
    }

    public void PlayBackMusic(string name)
    {
        if (backMusic==null)
        {
            GameObject backMusicObj = new GameObject("BackMusic");
            backMusic = backMusicObj.AddComponent<AudioSource>();
        }

        ResourceLoadManager.Instance.LoadAsync<AudioClip>("Audio/Music/"+name,(musicClip)=> 
        {
            backMusic.clip = musicClip;
            backMusic.loop = true;
            backMusic.Play();
        });

    }

    public void ChangeBackMusicVolume(float volume)
    {
        if (backMusic == null) return;
        backMusic.volume = volume;
    }

    public void PauseBackMusic()
    {
        if (backMusic == null) return;
        backMusic.Pause();
    }

    public void StopBackMusic()
    {
        if (backMusic == null) return;

        backMusic.Stop();
    }

    public void ChangeSoundVolume(float volume)
    {
        for (int i = 0; i < soundList.Count; i++)
        {
            soundList[i].volume = volume;
        }
    }

    public void PlaySound(string name,UnityAction<AudioSource> callBack=null)
    {
        if (soundObj == null) soundObj = new GameObject("Sound");
        
        ResourceLoadManager.Instance.LoadAsync<AudioClip>("Audio/Sound/" + name, (soundClip) =>
        {
            AudioSource sound = soundObj.AddComponent<AudioSource>();
            sound.clip = soundClip;
            sound.Play();
            soundList.Add(sound);

            if (callBack != null) callBack(sound);
        });
    }
    public void StopSound(AudioSource sound)
    {
        if (soundList.Contains(sound))
        {
            soundList.Remove(sound);
            sound.Stop();
            GameObject.Destroy(sound);
        }
    }
}
